package com.whfc.cncit.helmet.queue;

import com.alibaba.fastjson.JSON;
import com.whfc.cncit.constant.CncitConst;
import com.whfc.cncit.entity.CncitDwMsgPS;
import com.whfc.common.constant.QueueConst;
import com.whfc.emp.dto.AppBroadcastRecordEmpDTO;
import com.whfc.emp.enums.AppBroadcastSendState;
import com.whfc.hdc.service.AppDeviceService;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : qzexing
 * @version : 1.0
 * @date : 2020/7/3 16:58
 */
@Component
@RabbitListener(queues = QueueConst.EMP_HELMET_BOARDCAST)
public class HelmetBroadcastQueueMessageListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @DubboReference(interfaceClass = AppDeviceService.class, version = "1.0.0")
    private AppDeviceService commonDeviceService;

    @RabbitHandler
    public void onMessage(String msg) {
        AppBroadcastRecordEmpDTO recordEmpDTO = JSON.parseObject(msg, AppBroadcastRecordEmpDTO.class);
        logger.info("recordEmpDTO:{}", recordEmpDTO);
        Integer deviceId = recordEmpDTO.getDeviceId();
        Session session = sessionManager.getSessionByDeviceId(deviceId);
        if (session == null) {
            //修改广播状态为未发送
            recordEmpDTO.setState(AppBroadcastSendState.UNSENT.getValue());
            try {
                amqpTemplate.convertAndSend(QueueConst.EMP_HELMET_BOARDCAST_STATE, JSON.toJSONString(recordEmpDTO));
            } catch (Exception e) {
                logger.warn("发送消息失败.", e);
            }
            return;
        }

        //发送广播
        CncitDwMsgPS cncitDwMsgPS = new CncitDwMsgPS();
        cncitDwMsgPS.setType(CncitConst.CMD_TTSD);
        cncitDwMsgPS.setParam(recordEmpDTO.getContent());
        cncitDwMsgPS.setDeviceCode(recordEmpDTO.getCode());
        logger.info("发送消息:{} ", cncitDwMsgPS);
        session.getChannel().writeAndFlush(cncitDwMsgPS);
    }
}
